package com.sailfish.springbootdemo.service.db2.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.common.DB2Config;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db2.*;
import com.sailfish.springbootdemo.dao.db4.UserDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db2.*;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.pojo.db4.OperateLog;
import com.sailfish.springbootdemo.pojo.db4.User;
import com.sailfish.springbootdemo.service.db2.*;
import com.sailfish.springbootdemo.service.db4.OperateLogService;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.HttpUtil;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CapacityMatchServiceImpl implements CapacityMatchService {

    @Autowired
    private PcbSonFactoryInfoDao pcbSonFactoryInfoDao;
    @Autowired
    private PcbCapacityParamService pcbCapacityParamService;
    @Autowired
    private PcbSpecialProcessService pcbSpecialProcessService;
    @Autowired
    private PcbMaterialService pcbMaterialService;
    @Autowired
    private PcbMatchParamDao pcbMatchParamDao;
    @Autowired
    private PcbMatchFactoryValueDao pcbMatchFactoryValueDao;
    @Autowired
    private PcbParentFactoryInfoService pcbParentFactoryInfoService;
    @Autowired
    private PcbOpenCapacityApproveProcessDao pcbOpenCapacityApproveProcessDao;
    @Autowired
    private PcbOpenCapacityAuthenticationDao pcbOpenCapacityAuthenticationDao;
    @Autowired
    private PcbOpenCapacityFileDao pcbOpenCapacityFileDao;
    @Autowired
    private PcbPermissionConfigDao permissionConfigDao;
    @Autowired
    private PcbCapacityDataApproveDao pcbCapacityDataApproveDao;
    @Autowired
    private PcbCapacityApproveDetailDao pcbCapacityApproveDetailDao;
    @Autowired
    private PcbCapacityApproveDetailFileDao pcbCapacityApproveDetailFileDao;
    @Autowired
    private PcbApproveConfigDao pcbApproveConfigDao;
    @Autowired
    ThirdApiService thirdApiService;
    @Autowired
    private PcbApproveProcessDao pcbApproveProcessDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private OperateService operateService;
    @Autowired
    private OperateLogService operateLogService;
    @Value("${personal.config.env}")
    String env;

    @Override
    public List<CapacityMatch> getAll(String data) {
        List<PcbSonFactoryInfo> sonFactoryInfoList = pcbSonFactoryInfoDao.getAllByLimit(null);
        JSONObject jsonObject = JSONObject.parseObject(data);

        JSONArray jsonArray = jsonObject.getJSONArray("pcbTemplateList");
        JSONArray jsonArray1 = jsonObject.getJSONArray("pcbSpecialProcessId");
        JSONArray jsonArray2 = jsonObject.getJSONArray("material");

        Map<String, List<CapacityMatch>> listMap = new HashMap<>();
        if (jsonArray != null && jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jo = (JSONObject) jsonArray.get(i);
                String paramKey = jo.getString("pcbMatchParamKey");
                String value = jo.getString("pcbMatchParamValue");
                PcbSizeParam byParamKey = pcbMatchParamDao.getByParamKey(paramKey);
                String paramName = byParamKey.getPcbMatchParamName();
                if (!StringUtils.isBlank(value) && byParamKey != null) {
                    Integer pcbMatchParamRuleType = byParamKey.getPcbMatchParamRuleType();
                    if (pcbMatchParamRuleType == 6) {
                        //表面处理方式,匹配规则：包含
                        List<CapacityMatch> capacityMatchFactoryDataContain = getCapacityMatchFactoryDataContain(sonFactoryInfoList, paramKey, paramName, value);
                        listMap.put(paramKey, capacityMatchFactoryDataContain);
                    } else {
                        //其他参数类型,匹配规则：比较大小
                        double value2 = Double.parseDouble(value);
                        List<CapacityMatch> capacityMatchFactoryDataOther = getCapacityMatchFactoryData(sonFactoryInfoList, paramKey, paramName, value2, byParamKey.getPcbMatchParamRuleType());
                        listMap.put(paramKey, capacityMatchFactoryDataOther);
                    }
                } else {
                    List<CapacityMatch> capacityMatchFactoryDataOther = new ArrayList<>();
                    for (int n = 0; n < sonFactoryInfoList.size(); n++) {
                        CapacityMatch capacityMatch = new CapacityMatch();
                        capacityMatch.setPcbSonFactoryInfoId(sonFactoryInfoList.get(i).getPcbSonFactoryId());
                        capacityMatch.setParamKey(paramKey);
                        capacityMatch.setParamName(paramName);
                        capacityMatch.setIsSatisfied("是");
                        capacityMatch.setPcbSonFactoryInfo(sonFactoryInfoList.get(i));
                        capacityMatch.setReason("");
                        capacityMatchFactoryDataOther.add(capacityMatch);
                    }
                    listMap.put(paramKey, capacityMatchFactoryDataOther);
                }
            }
        }

        Integer openStatus = null;
        if (jsonObject.getInteger("openStatus") != null) {
            openStatus = jsonObject.getInteger("openStatus");
        }
        List<PcbMaterialLibrary> materialLibraryList = new ArrayList<>();
        for (int i = 0; i < jsonArray2.size(); i++) {
            PcbMaterialLibrary pcbMaterialLibrary = new PcbMaterialLibrary();
            pcbMaterialLibrary.setRowKey(jsonArray2.getString(i));
            materialLibraryList.add(pcbMaterialLibrary);
        }
        List<CapacityMatch> capacityMatchFactory2 = pcbMaterialService.getCapacityMatch(sonFactoryInfoList, materialLibraryList, openStatus);

        List<PcbSpecialProcessInfo> pcbSpecialProcessInfoList = new ArrayList<>();
        for (int i = 0; i < jsonArray1.size(); i++) {
            Integer id = jsonArray1.getInteger(i);
            PcbSpecialProcessInfo pcbSpecialProcessInfo = pcbSpecialProcessService.getById(id);
            pcbSpecialProcessInfoList.add(pcbSpecialProcessInfo);
        }

        List<CapacityMatch> capacityMatchFactory3 = pcbSpecialProcessService.getCapacityMatch(sonFactoryInfoList, pcbSpecialProcessInfoList);

        List<CapacityMatch> result = new ArrayList<>();
        for (int i = 0; i < sonFactoryInfoList.size(); i++) {
            Integer sonFId = sonFactoryInfoList.get(i).getPcbSonFactoryId();
            boolean flag = true;
            String reason = "";
            for (Map.Entry<String, List<CapacityMatch>> kv : listMap.entrySet()) {
                List<CapacityMatch> matchList = kv.getValue();
                for (int j = 0; j < matchList.size(); j++) {
                    if (matchList.get(j).getPcbSonFactoryInfoId() == sonFId) {
                        if (matchList.get(j).getIsSatisfied().equals("否")) {
                            flag = false;
                            reason += matchList.get(j).getReason() + "\r\n";
                        }
                    }
                }
            }
            for (int j = 0; j < capacityMatchFactory2.size(); j++) {
                if (capacityMatchFactory2.get(j).getPcbSonFactoryInfoId() == sonFId) {
                    if (capacityMatchFactory2.get(j).getIsSatisfied().equals("否")) {
                        flag = false;
                        reason += capacityMatchFactory2.get(j).getReason() + "\r\n";
                    }
                }
            }
            for (int j = 0; j < capacityMatchFactory3.size(); j++) {
                if (capacityMatchFactory3.get(j).getPcbSonFactoryInfoId() == sonFId) {
                    if (capacityMatchFactory3.get(j).getIsSatisfied().equals("否")) {
                        flag = false;
                        reason += capacityMatchFactory3.get(j).getReason() + "\r\n";
                    }
                }
            }
            CapacityMatch capacityMatch = new CapacityMatch();
            capacityMatch.setPcbSonFactoryInfoId(sonFactoryInfoList.get(i).getPcbSonFactoryId());
            capacityMatch.setPcbSonFactoryInfo(sonFactoryInfoList.get(i));
            if (flag) {
                capacityMatch.setIsSatisfied("是");
            } else {
                capacityMatch.setIsSatisfied("否");
            }
            capacityMatch.setReason(reason);
            result.add(capacityMatch);
        }

        return result;
    }

    public List<CapacityMatch> getCapacityMatchFactoryData(List<PcbSonFactoryInfo> sonFactoryInfoList, String paramKey, String paramName, Double requireData, Integer ruleType) {
        List<CapacityMatch> satisfiedFactory = new ArrayList<>();
        //找到对应的参数
        PcbSizeFactoryValue search = new PcbSizeFactoryValue();
        search.setPcbMatchParamKey(paramKey);
        List<PcbSizeFactoryValue> pcbSizeFactoryValueList = pcbMatchFactoryValueDao.getByLimit(search);
        Map<String, String> mapData = new HashMap<>();
        if (pcbSizeFactoryValueList != null && pcbSizeFactoryValueList.size() > 0) {
            for (int i = 0; i < pcbSizeFactoryValueList.size(); i++) {
                String key = pcbSizeFactoryValueList.get(i).getSonFactoryId() + "-" + pcbSizeFactoryValueList.get(i).getPcbMatchParamKey();
                mapData.put(key, pcbSizeFactoryValueList.get(i).getPcbMatchParamValue());
            }
            for (int i = 0; i < sonFactoryInfoList.size(); i++) {
                if (requireData == null) {
                    CapacityMatch capacityMatch = new CapacityMatch();
                    capacityMatch.setPcbSonFactoryInfoId(sonFactoryInfoList.get(i).getPcbSonFactoryId());
                    capacityMatch.setParamKey(paramKey);
                    capacityMatch.setParamName(paramName);
                    capacityMatch.setIsSatisfied("是");
                    capacityMatch.setPcbSonFactoryInfo(sonFactoryInfoList.get(i));
                    satisfiedFactory.add(capacityMatch);
                } else {
                    String key = sonFactoryInfoList.get(i).getPcbSonFactoryId() + "-" + paramKey;
                    String value = mapData.get(key);
                    boolean falg = false;
                    if (!StringUtils.isEmpty(value) && ruleType != null) {
                        Double value2 = Double.parseDouble(value);

                        if (ruleType == 1 && value2 >= requireData) {
                            falg = true;
                        }
                        if (ruleType == 2 && value2 <= requireData) {
                            falg = true;
                        }
                        if (ruleType == 3 && value2 > requireData) {
                            falg = true;
                        }
                        if (ruleType == 4 && value2 < requireData) {
                            falg = true;
                        }
                        if (ruleType == 5 && value2 == requireData) {
                            falg = true;
                        }
                    }
                    if (falg) {
                        CapacityMatch capacityMatch = new CapacityMatch();
                        capacityMatch.setPcbSonFactoryInfoId(sonFactoryInfoList.get(i).getPcbSonFactoryId());
                        capacityMatch.setParamKey(paramKey);
                        capacityMatch.setParamName(paramName);
                        capacityMatch.setIsSatisfied("是");
                        capacityMatch.setPcbSonFactoryInfo(sonFactoryInfoList.get(i));
                        satisfiedFactory.add(capacityMatch);
                    } else {
                        CapacityMatch capacityMatch = new CapacityMatch();
                        capacityMatch.setPcbSonFactoryInfoId(sonFactoryInfoList.get(i).getPcbSonFactoryId());
                        capacityMatch.setParamKey(paramKey);
                        capacityMatch.setParamName(paramName);
                        capacityMatch.setIsSatisfied("否");
                        capacityMatch.setPcbSonFactoryInfo(sonFactoryInfoList.get(i));
                        capacityMatch.setReason("单板" + paramName + "为:" + requireData + ",板厂" + paramName + "为:" + value);
                        satisfiedFactory.add(capacityMatch);
                    }
                }
            }
        } else {
            for (int i = 0; i < sonFactoryInfoList.size(); i++) {
                CapacityMatch capacityMatch = new CapacityMatch();
                capacityMatch.setPcbSonFactoryInfoId(sonFactoryInfoList.get(i).getPcbSonFactoryId());
                capacityMatch.setParamKey(paramKey);
                capacityMatch.setParamName(paramName);
                capacityMatch.setIsSatisfied("否");
                capacityMatch.setPcbSonFactoryInfo(sonFactoryInfoList.get(i));
                capacityMatch.setReason("单板" + paramName + "为:" + requireData + ",板厂" + paramName + "为:");
                satisfiedFactory.add(capacityMatch);
            }
        }
        return satisfiedFactory;
    }

    public List<CapacityMatch> getCapacityMatchFactoryDataContain(List<PcbSonFactoryInfo> sonFactoryInfoList, String paramKey, String paramName, String requireData) {
        List<CapacityMatch> satisfiedFactory = new ArrayList<>();
        //找到对应的参数
        PcbSizeFactoryValue search = new PcbSizeFactoryValue();
        search.setPcbMatchParamKey(paramKey);
        List<PcbSizeFactoryValue> pcbSizeFactoryValueList = pcbMatchFactoryValueDao.getByLimit(search);
        Map<String, String> mapData = new HashMap<>();
        if (pcbSizeFactoryValueList != null && pcbSizeFactoryValueList.size() > 0) {
            for (int i = 0; i < pcbSizeFactoryValueList.size(); i++) {
                String key = pcbSizeFactoryValueList.get(i).getSonFactoryId() + "-" + pcbSizeFactoryValueList.get(i).getPcbMatchParamKey();
                mapData.put(key, pcbSizeFactoryValueList.get(i).getPcbMatchParamValue());
            }
            for (int i = 0; i < sonFactoryInfoList.size(); i++) {
                if (requireData == null) {
                    CapacityMatch capacityMatch = new CapacityMatch();
                    capacityMatch.setPcbSonFactoryInfoId(sonFactoryInfoList.get(i).getPcbSonFactoryId());
                    capacityMatch.setParamKey(paramKey);
                    capacityMatch.setParamName(paramName);
                    capacityMatch.setIsSatisfied("是");
                    capacityMatch.setPcbSonFactoryInfo(sonFactoryInfoList.get(i));
                    satisfiedFactory.add(capacityMatch);
                } else {
                    String key = sonFactoryInfoList.get(i).getPcbSonFactoryId() + "-" + paramKey;
                    String value = mapData.get(key) + ",";
                    String[] splits = requireData.split(",");
                    boolean flag = false;
                    for (int k = 0; k < splits.length; k++) {
                        if (value.contains(splits[k] + ",")) {
                            CapacityMatch capacityMatch = new CapacityMatch();
                            capacityMatch.setPcbSonFactoryInfoId(sonFactoryInfoList.get(i).getPcbSonFactoryId());
                            capacityMatch.setParamKey(paramKey);
                            capacityMatch.setParamName(paramName);
                            capacityMatch.setIsSatisfied("是");
                            capacityMatch.setPcbSonFactoryInfo(sonFactoryInfoList.get(i));
                            satisfiedFactory.add(capacityMatch);
                            flag = true;
                            break;
                        }
                    }
                    if (!flag) {
                        CapacityMatch capacityMatch = new CapacityMatch();
                        capacityMatch.setPcbSonFactoryInfoId(sonFactoryInfoList.get(i).getPcbSonFactoryId());
                        capacityMatch.setParamKey(paramKey);
                        capacityMatch.setParamName(paramName);
                        capacityMatch.setIsSatisfied("否");
                        capacityMatch.setPcbSonFactoryInfo(sonFactoryInfoList.get(i));
                        capacityMatch.setReason("单板" + paramName + "为:" + requireData + ",板厂" + paramName + "为:" + value);
                        satisfiedFactory.add(capacityMatch);
                    }
                }
            }
        } else {
            for (int i = 0; i < sonFactoryInfoList.size(); i++) {
                CapacityMatch capacityMatch = new CapacityMatch();
                capacityMatch.setPcbSonFactoryInfoId(sonFactoryInfoList.get(i).getPcbSonFactoryId());
                capacityMatch.setParamKey(paramKey);
                capacityMatch.setParamName(paramName);
                capacityMatch.setIsSatisfied("否");
                capacityMatch.setPcbSonFactoryInfo(sonFactoryInfoList.get(i));
                capacityMatch.setReason("单板" + paramName + "为:" + requireData + ",板厂" + paramName + "为:");
                satisfiedFactory.add(capacityMatch);
            }
        }
        return satisfiedFactory;
    }

    @Override
    public List<PcbSizeParam> getMatchParam(Integer status) {
        PcbSizeParam param = new PcbSizeParam();
        param.setStatus(status);
        return pcbMatchParamDao.getByLimit(param);
    }

    @Override
    public PcbSizeParam getMatchParamByKey(String paramKey) {
        if (StringUtils.isBlank(paramKey)) {
            return null;
        } else {
            return pcbMatchParamDao.getByParamKey(paramKey);
        }

    }

    @Override
    public PcbSizeParam getMatchParamByName(String paramName) {
        return pcbMatchParamDao.getByParamName(paramName);
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result insertOrUpdateMatchParam(String data) {
        String userId = UserHeaderHolder.getUserId();
        JSONObject jsonObject = JSONObject.parseObject(data);
        String mode = jsonObject.getString("mode");
        String paramName = jsonObject.getString("pcbMatchParamName");
        String paramKey = jsonObject.getString("pcbMatchParamKey");
        String paramOptions = jsonObject.getString("paramOptions");
        Integer paramRuleType = jsonObject.getInteger("pcbMatchParamRuleType");
        Integer paramType = jsonObject.getInteger("pcbMatchParamType");
        Integer status = jsonObject.getInteger("status");
        Integer sort = jsonObject.getInteger("sort");
        Integer id = jsonObject.getInteger("id");
        PcbSizeParam pcbSizeParam = new PcbSizeParam();
        pcbSizeParam.setPcbMatchParamName(paramName);
        pcbSizeParam.setPcbMatchParamRuleType(paramRuleType);
        pcbSizeParam.setPcbMatchParamKey(paramKey);
        pcbSizeParam.setPcbMatchParamType(paramType);
        pcbSizeParam.setStatus(status);
        pcbSizeParam.setSort(sort);
        pcbSizeParam.setParamOptions(paramOptions);
        if (StringUtils.isBlank(paramName)) {
            return ResultUtil.error(500, "参数pcbMatchParamName名为空", "param pcbMatchParamName is null", null);
        }
        if (StringUtils.isBlank(paramKey)) {
            return ResultUtil.error(500, "参数pcbMatchParamKey为空", "param pcbMatchParamKey is null", null);
        }
        if (paramRuleType == null) {
            return ResultUtil.error(500, "参数pcbMatchParamRuleType为空", "param pcbMatchParamRuleType is null", null);
        }
        if (paramType == null) {
            return ResultUtil.error(500, "参数pcbMatchParamType为空", "param pcbMatchParamType is null", null);
        }
        try {
            if (mode.equals("add")) {
                pcbSizeParam.setCreateTime(new Date());
                pcbSizeParam.setCreateUser(userId);
                Integer insert = pcbMatchParamDao.insert(pcbSizeParam);
                if (insert > 0) {
                    operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB能力匹配尺寸参数定义", 1, 1, new Date(), null, JSONObject.toJSONString(pcbSizeParam)));
                } else {
                    return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                }
            } else {
                if (id == null) {
                    return ResultUtil.error(500, "参数id为空", "param id is null", null);
                }
                PcbSizeParam pcbSizeParam1 = pcbMatchParamDao.getById(id);
                String oldData = JSONObject.toJSONString(pcbSizeParam1);
                pcbSizeParam.setId(id);
                pcbSizeParam.setUpdateTime(new Date());
                pcbSizeParam.setUpdateUser(userId);

                Integer update = pcbMatchParamDao.update(pcbSizeParam);
                if (update > 0) {
                    operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB能力匹配尺寸参数定义", 3, 1, new Date(), oldData, JSONObject.toJSONString(pcbSizeParam)));
                } else {
                    return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                }
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result deleteMatchParam(Integer id) {
        if (id == null) {
            return ResultUtil.error(500, "参数id为空", "param id is null", null);
        }
        String userId = UserHeaderHolder.getUserId();
        try {
            PcbSizeParam pcbSizeParam1 = pcbMatchParamDao.getById(id);
            String oldData = JSONObject.toJSONString(pcbSizeParam1);
            Integer update = pcbMatchParamDao.delete(id);
            if (update > 0) {
                PcbSizeParam pcbSizeParam2 = pcbMatchParamDao.getById(id);
                String newData = JSONObject.toJSONString(pcbSizeParam2);
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB能力匹配尺寸参数定义", 2, 1, new Date(), oldData, newData));
                return ResultUtil.success(null);
            } else {
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public List<CapacityMatchData> getMatchFactoryValue(List<Integer> sonFactoryInfoList, int type) {

        String queryType = "";
        if(type == 1){
            queryType = "基础能力";
        }
        else{
            queryType = "开放能力查看";
        }
        final String userId = UserHeaderHolder.getUserId();
        OperateLog operateLog = new OperateLog(2,Integer.parseInt(userId) ,queryType,4,1,new Date(), UserHeaderHolder.getDomainAccount(), UserHeaderHolder.getIpAddress(), UserHeaderHolder.getNetworkSeg());
        boolean aa = operateLogService.addOperateLog(operateLog);


        List<PcbSonFactoryInfo> pcbSonFactoryInfoList = new ArrayList<>();
        for (int i = 0; i < sonFactoryInfoList.size(); i++) {
            PcbSonFactoryInfo pcbSonFactoryInfo = new PcbSonFactoryInfo();
            pcbSonFactoryInfo.setPcbSonFactoryId(sonFactoryInfoList.get(i));
            pcbSonFactoryInfoList.add(pcbSonFactoryInfo);
        }
        List<CapacityMatchData> capacityMatchDataList = new ArrayList<>();
        List<PcbSizeFactoryValue> byLimit = pcbMatchFactoryValueDao.getByLimit(null);
        if (byLimit != null) {
            Map<String, String> map = new HashMap<>();
            for (int i = 0; i < byLimit.size(); i++) {
                String key = byLimit.get(i).getSonFactoryId() + "-" + byLimit.get(i).getPcbMatchParamKey();
                map.put(key, byLimit.get(i).getPcbMatchParamValue());
            }
            PcbSizeParam search = new PcbSizeParam();
            search.setStatus(1);
            List<PcbSizeParam> pcbSizeParamList = pcbMatchParamDao.getByLimit(search);

            for (int i = 0; i < pcbSizeParamList.size(); i++) {
                String paramKey = pcbSizeParamList.get(i).getPcbMatchParamKey();
                CapacityMatchData capacityMatchData = new CapacityMatchData();
                capacityMatchData.setBigType("PCB尺寸");
                capacityMatchData.setParamName(pcbSizeParamList.get(i).getPcbMatchParamName());
                capacityMatchData.setParamKey(paramKey);
                capacityMatchData.setParamOption(pcbSizeParamList.get(i).getParamOptions());
                capacityMatchData.setParamRule(pcbSizeParamList.get(i).getPcbMatchParamRuleType());
                capacityMatchData.setParamValueType(pcbSizeParamList.get(i).getPcbMatchParamType());
                List<ParamData> factoryData = new ArrayList<>();
                for (int j = 0; j < sonFactoryInfoList.size(); j++) {
                    String key2 = sonFactoryInfoList.get(j) + "-" + paramKey;
                    if (map.containsKey(key2)) {
                        factoryData.add(new ParamData(sonFactoryInfoList.get(j), map.get(key2)));
                    } else {
                        factoryData.add(new ParamData(sonFactoryInfoList.get(j), null));
                    }
                }
                capacityMatchData.setFactoryData(factoryData);
                capacityMatchDataList.add(capacityMatchData);
            }
        }
        if (type == 2) {
            List<CapacityMatchData> materialFactoryValue = getMaterialFactoryValue(pcbSonFactoryInfoList);
            List<CapacityMatchData> specialProcessFactoryValue = getSpecialProcessFactoryValue(pcbSonFactoryInfoList);
            if (materialFactoryValue != null) {
                capacityMatchDataList.addAll(materialFactoryValue);
            }
            if (specialProcessFactoryValue != null) {
                capacityMatchDataList.addAll(specialProcessFactoryValue);
            }
        }
        return capacityMatchDataList;
    }

    @Override
    public List<PcbSizeFactoryValue> getPcbMatchFactoryValue(Integer sonFactoryInfoId) {
        PcbSizeFactoryValue search = new PcbSizeFactoryValue();
        search.setSonFactoryId(sonFactoryInfoId);
        List<PcbSizeFactoryValue> byLimit = pcbMatchFactoryValueDao.getByLimit(search);
        return byLimit;
    }

    List<CapacityMatchData> getMaterialFactoryValue(List<PcbSonFactoryInfo> sonFactoryInfoList) {
        List<PcbMaterialLibrary> pcbMaterialData = pcbMaterialService.getPcbMaterialData(null);
        List<CapacityMatchData> capacityMatchDataList = new ArrayList<>();
        for (int i = 0; i < pcbMaterialData.size(); i++) {
            CapacityMatchData capacityMatchData = new CapacityMatchData();
            capacityMatchData.setBigType("板材");
            capacityMatchData.setParamName(pcbMaterialData.get(i).getParamValue());
            List<ParamData> paramDataList = new ArrayList<>();
            List<SpecialProcessInfo> factoryOpenStatusList = pcbMaterialData.get(i).getFactoryOpenStatusList();
            for (int j = 0; j < factoryOpenStatusList.size(); j++) {
                String value2 = factoryOpenStatusList.get(j).getSatisfied() == null ? null : factoryOpenStatusList.get(j).getSatisfied().toString();
                paramDataList.add(new ParamData(factoryOpenStatusList.get(j).getFactoryId(), value2));
            }
            capacityMatchData.setFactoryData(paramDataList);
            capacityMatchDataList.add(capacityMatchData);
        }
        return capacityMatchDataList;
    }

    List<CapacityMatchData> getSpecialProcessFactoryValue(List<PcbSonFactoryInfo> sonFactoryInfoList) {
        List<PcbSpecialProcessInfo> pcbSpecialProcessData = pcbSpecialProcessService.getPcbSpecialProcessData(null, null, null, sonFactoryInfoList);

        List<CapacityMatchData> capacityMatchDataList = new ArrayList<>();
        for (int i = 0; i < pcbSpecialProcessData.size(); i++) {
            CapacityMatchData capacityMatchData = new CapacityMatchData();
            capacityMatchData.setBigType("特殊工艺");
            capacityMatchData.setParamName(pcbSpecialProcessData.get(i).getPcbSpecialProcessName());
            List<ParamData> paramDataList = new ArrayList<>();
            List<SpecialProcessInfo> factoryOpenStatusList = pcbSpecialProcessData.get(i).getData();
            for (int j = 0; j < factoryOpenStatusList.size(); j++) {
                String value2 = factoryOpenStatusList.get(j).getSatisfied() == null ? null : factoryOpenStatusList.get(j).getSatisfied().toString();
                paramDataList.add(new ParamData(factoryOpenStatusList.get(j).getFactoryId(), value2));
            }
            capacityMatchData.setFactoryData(paramDataList);
            capacityMatchDataList.add(capacityMatchData);
        }
        return capacityMatchDataList;
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result insertOrUpdateMatchFactoryValue(String data) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        JSONArray jsonArray = jsonObject.getJSONArray("pcbTemplateList");
        if (jsonArray == null || jsonArray.size() == 0) {
            return ResultUtil.error(500, "pcbTemplateList 为空", "pcbTemplateList is null", null);
        }
        Integer sonFactoryId = jsonObject.getInteger("sonFactoryId");
        if (sonFactoryId == null) {
            return ResultUtil.error(500, "参数sonFactoryId为空", "param sonFactoryId is null", null);
        }
        String userId = UserHeaderHolder.getUserId();
        try {
            for (int i = 0; i < jsonArray.size(); i++) {
                PcbSizeFactoryValue pcbSizeFactoryValue = new PcbSizeFactoryValue();
                JSONObject jo = (JSONObject) jsonArray.get(i);
                String pcbMatchParamKey = jo.getString("pcbMatchParamKey");
                String pcbMatchParamValue = jo.getString("pcbMatchParamValue");
                Integer id = jo.getInteger("id");
                pcbSizeFactoryValue.setPcbMatchParamValue(pcbMatchParamValue);
                pcbSizeFactoryValue.setPcbMatchParamKey(pcbMatchParamKey);
                pcbSizeFactoryValue.setSonFactoryId(sonFactoryId);
                if (StringUtils.isBlank(pcbMatchParamValue)) {
                    return ResultUtil.error(500, "参数pcbMatchParamValue名为空", "param pcbMatchParamValue is null", null);
                }
                if (StringUtils.isBlank(pcbMatchParamKey)) {
                    return ResultUtil.error(500, "参数paramKey为空", "param paramKey is null", null);
                }
                if (id == null) {
                    pcbSizeFactoryValue.setCreateTime(new Date());
                    pcbSizeFactoryValue.setCreateUser(userId);
                    int count = pcbMatchFactoryValueDao.insert(pcbSizeFactoryValue);
                    if (count > 0) {
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB能力匹配PCB尺寸", 1, 1, new Date(), null, JSONObject.toJSONString(pcbSizeFactoryValue)));
                    }
                    else {
                        return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                    }
                } else {
                    if (sonFactoryId == null) {
                        return ResultUtil.error(500, "参数sonFactoryId为空", "param sonFactoryId is null", null);
                    }
                    PcbSizeFactoryValue byId = pcbMatchFactoryValueDao.getById(id);
                    pcbSizeFactoryValue.setUpdateTime(new Date());
                    pcbSizeFactoryValue.setUpdateUser(userId);
                    pcbSizeFactoryValue.setId(id);
                    int count = pcbMatchFactoryValueDao.update(pcbSizeFactoryValue);
                    if (count > 0) {
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB能力匹配PCB尺寸", 1, 1, new Date(), JSONObject.toJSONString(byId), JSONObject.toJSONString(pcbSizeFactoryValue)));
                    }
                    else {
                        return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                    }
                }
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result insertOrUpdateMatchFactoryValue2(String data) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        String paramKey = jsonObject.getString("paramKey");
        if (StringUtils.isBlank(paramKey)) {
            return ResultUtil.error(500, "参数paramKey为空", "param paramKey is null", null);
        }
        String userId = UserHeaderHolder.getUserId();
        List<PcbSonFactoryInfo> allFactorys = pcbSonFactoryInfoDao.getAllByLimit(null);

        try {
            for (PcbSonFactoryInfo sonFac : allFactorys) {
                Integer sonFacId = sonFac.getPcbSonFactoryId();
                String factoryValue = jsonObject.getString(sonFacId.toString());

                PcbSizeFactoryValue pcbSizeFactoryValue = new PcbSizeFactoryValue();
                pcbSizeFactoryValue.setPcbMatchParamValue(factoryValue);
                pcbSizeFactoryValue.setPcbMatchParamKey(paramKey);
                pcbSizeFactoryValue.setSonFactoryId(sonFacId);
                pcbSizeFactoryValue.setStatus(1);
                pcbSizeFactoryValue.setSort(100);

                PcbSizeFactoryValue search = new PcbSizeFactoryValue();
                search.setPcbMatchParamKey(paramKey);
                search.setSonFactoryId(sonFacId);
                final List<PcbSizeFactoryValue> byLimit = pcbMatchFactoryValueDao.getByLimit(search);
                if (byLimit != null && byLimit.size() > 0){
                    PcbSizeFactoryValue old = byLimit.get(0);
                    String oldData = JSONObject.toJSONString(old);
                    pcbSizeFactoryValue.setUpdateTime(new Date());
                    pcbSizeFactoryValue.setUpdateUser(userId);
                    pcbSizeFactoryValue.setId(old.getId());
                    int count = pcbMatchFactoryValueDao.update(pcbSizeFactoryValue);
                    if (count > 0) {
                        String newData = JSONObject.toJSONString(pcbMatchFactoryValueDao.getByLimit(search));
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB能力匹配PCB尺寸", 3, 1, new Date(), oldData, newData));
                    }
                    else {
                        return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                    }
                } else {
                    pcbSizeFactoryValue.setCreateUser(userId);
                    pcbSizeFactoryValue.setCreateTime(new Date());
                    int count = pcbMatchFactoryValueDao.insert(pcbSizeFactoryValue);
                    if (count > 0) {
                        String newData = JSONObject.toJSONString(pcbMatchFactoryValueDao.getByLimit(search));
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB能力匹配PCB尺寸", 1, 1, new Date(), null, newData));
                    }
                    else {
                        return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                    }
                }

            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result deleteMatchFactoryValue(Integer id) {
        return null;
    }

    @Value("${personal.config.file.file-save-url}")
    private String rootPath;

    @Override
    public Result outputParamTemplate(String data) throws IOException {
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            JSONArray jsonArray = jsonObject.getJSONArray("pcbTemplateList");
            JSONArray jsonArray1 = jsonObject.getJSONArray("pcbSpecialProcessId");
            JSONArray jsonArray2 = jsonObject.getJSONArray("material");
            Map<String, String> mapData = new HashMap<>();
            if (jsonArray != null) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jo = (JSONObject) jsonArray.get(i);
                    String paramKey = jo.getString("pcbMatchParamKey");
                    String value = jo.getString("pcbMatchParamValue");
                    mapData.put(paramKey, value);
                }
            }

            List<PcbMaterialLibrary> materialLibraryList = new ArrayList<>();
            Integer openStatus = null;
            if (jsonObject.getInteger("openStatus") != null) {
                openStatus = jsonObject.getInteger("openStatus");
            }
            PcbMaterialParam paramMaterial = pcbMaterialService.getByParamName("板材");
            if (paramMaterial != null) {
                for (int i = 0; i < jsonArray2.size(); i++) {

                    PcbMaterialLibrary pcbMaterialLibrary = new PcbMaterialLibrary();
                    pcbMaterialLibrary.setRowKey(jsonArray2.getString(i));
                    pcbMaterialLibrary.setParamKey(paramMaterial.getParamKey());
                    PcbMaterialLibrary allByRowKeyAndParamKey = pcbMaterialService.getAllByRowKeyAndParamKey(paramMaterial.getParamKey(), jsonArray2.getString(i));
                    materialLibraryList.add(allByRowKeyAndParamKey);
                }
            }


            List<PcbSpecialProcessInfo> pcbSpecialProcessInfoList = new ArrayList<>();
            for (int i = 0; i < jsonArray1.size(); i++) {
                Integer id = jsonArray1.getInteger(i);
                PcbSpecialProcessInfo pcbSpecialProcessInfo = pcbSpecialProcessService.getById(id);
                pcbSpecialProcessInfoList.add(pcbSpecialProcessInfo);
            }

            // 创建工作簿对象
            Workbook workbook = new XSSFWorkbook();
            // 创建工作表对象
            Sheet sheet = workbook.createSheet("Sheet1");
            sheet.setColumnWidth(0, 25 * 256);
            XSSFCellStyle setBorder = (XSSFCellStyle) workbook.createCellStyle();
            setBorder.setBorderBottom(BorderStyle.THIN);
            setBorder.setBorderLeft(BorderStyle.THIN);
            setBorder.setBorderRight(BorderStyle.THIN);
            setBorder.setBorderTop(BorderStyle.THIN);
            setBorder.setVerticalAlignment(VerticalAlignment.CENTER);
            setBorder.setAlignment(HorizontalAlignment.LEFT);
            //创建字体 加粗
            XSSFFont font = (XSSFFont) workbook.createFont();
            font.setBold(true);
            font.setFontHeight(11);
            setBorder.setFont(font);

            XSSFCellStyle setBorder2 = (XSSFCellStyle) workbook.createCellStyle();
            setBorder2.setBorderBottom(BorderStyle.THIN);
            setBorder2.setBorderLeft(BorderStyle.THIN);
            setBorder2.setBorderRight(BorderStyle.THIN);
            setBorder2.setBorderTop(BorderStyle.THIN);
            setBorder2.setVerticalAlignment(VerticalAlignment.CENTER);
            setBorder2.setAlignment(HorizontalAlignment.LEFT);

            Row rowT1 = sheet.createRow(0);
            Cell cell = rowT1.createCell(0);
            cell.setCellValue("PCB尺寸");
            cell.setCellStyle(setBorder);

            int rowIndex = 0;
            PcbSizeParam search = new PcbSizeParam();
            search.setStatus(1);
            List<PcbSizeParam> pcbSizeParamList = pcbMatchParamDao.getByLimit(search);
            for (int i = 0; i < pcbSizeParamList.size(); i = i + 2) {
                rowIndex++;
                Row rowT = sheet.createRow(rowIndex);
                Cell cellT1 = rowT.createCell(0);
                cellT1.setCellValue(pcbSizeParamList.get(i).getPcbMatchParamName() + ":");
                cellT1.setCellStyle(setBorder2);
                String paramKey = pcbSizeParamList.get(i).getPcbMatchParamKey();
                String s = mapData.get(paramKey);
                Cell cellT2 = rowT.createCell(1);
                cellT2.setCellValue(s);
                cellT2.setCellStyle(setBorder2);
                if (i + 1 < pcbSizeParamList.size()) {
                    Cell cellT3 = rowT.createCell(2);
                    cellT3.setCellValue(pcbSizeParamList.get(i + 1).getPcbMatchParamName() + ":");
                    cellT3.setCellStyle(setBorder2);
                    String paramKey2 = pcbSizeParamList.get(i + 1).getPcbMatchParamKey();
                    String s2 = mapData.get(paramKey2);
                    Cell cellT4 = rowT.createCell(3);
                    cellT4.setCellValue(s2);
                    cellT4.setCellStyle(setBorder2);
                }
            }
            rowIndex++;
            Row rowT2 = sheet.createRow(rowIndex);
            Cell cell2 = rowT2.createCell(0);
            cell2.setCellValue("损耗");
            cell2.setCellStyle(setBorder);
            rowIndex++;
            Row rowT3 = sheet.createRow(rowIndex);
            Cell cell3 = rowT3.createCell(0);
            cell3.setCellValue("耗损管控等级:");
            cell3.setCellStyle(setBorder2);
            Cell cell4 = rowT3.createCell(1);
            String s_openStatus = "";
            if (openStatus != null) {
                if (openStatus == 1) {
                    s_openStatus = "一级开放";
                } else if (openStatus == 2) {
                    s_openStatus = "二级开放";
                } else if (openStatus == 3) {
                    s_openStatus = "三级开放";
                } else if (openStatus == 4) {
                    s_openStatus = "不开放";
                }
            }

            cell4.setCellValue(s_openStatus);
            cell4.setCellStyle(setBorder2);
            rowIndex++;
            Row rowT5 = sheet.createRow(rowIndex);
            Cell cell5 = rowT5.createCell(0);
            cell5.setCellValue("特殊工艺");
            cell5.setCellStyle(setBorder);
            rowIndex++;
            Row rowT6 = sheet.createRow(rowIndex);
            Cell cell6 = rowT6.createCell(0);
            cell6.setCellValue("请选择特殊工艺:");
            cell6.setCellStyle(setBorder2);
            for (int i = 0; i < pcbSpecialProcessInfoList.size(); i++) {
                Cell cell7 = rowT6.createCell(i + 1);
                cell7.setCellValue(pcbSpecialProcessInfoList.get(i).getPcbSpecialProcessName());
                cell7.setCellStyle(setBorder2);
            }
            rowIndex++;
            Row rowT11 = sheet.createRow(rowIndex);
            Cell cell11 = rowT11.createCell(0);
            cell11.setCellValue("板材");
            cell11.setCellStyle(setBorder);
            rowIndex++;

            Row rowT8 = sheet.createRow(rowIndex);
            Cell cell8 = rowT8.createCell(0);
            cell8.setCellValue("请选择板材:");
            cell8.setCellStyle(setBorder2);

            for (int i = 0; i < materialLibraryList.size(); i++) {
                Cell cell9 = rowT8.createCell(i + 1);
                cell9.setCellValue(materialLibraryList.get(i).getParamValue());
                cell9.setCellStyle(setBorder2);
            }
            List<PcbParentFactoryInfo> bySonList = pcbParentFactoryInfoService.getAll(null, null, null, null, null, null, null, null, null, null, null, null, 1, null);

            rowIndex++;
            Row rowTitleEmpty = sheet.createRow(rowIndex);
            rowIndex++;

            int t1RowFlag = rowIndex;
            Row rowTitle1 = sheet.createRow(rowIndex);
            rowIndex++;
            Row rowTitle2 = sheet.createRow(rowIndex);
            rowIndex++;
            Row rowTitle3 = sheet.createRow(rowIndex);
            rowIndex++;
            Row rowTitle4 = sheet.createRow(rowIndex);
            List<CapacityMatch> all = getAll(data);
            Map<Integer, CapacityMatch> map = new HashMap<>();

            for (int i = 0; i < all.size(); i++) {
                Integer pcbSonId = all.get(i).getPcbSonFactoryInfoId();
                map.put(pcbSonId, all.get(i));
            }
            int colIndex = 0;
            int flag = 0;
            for (int i = 0; i < bySonList.size(); i++) {
                flag = colIndex;
                PcbParentFactoryInfo pcbParentFactoryInfo = bySonList.get(i);
                List<PcbSonFactoryInfo> sonFactoryInfos = pcbParentFactoryInfo.getSonFactoryInfos();

                Cell cell1 = rowTitle1.createCell(colIndex);
                cell1.setCellValue(pcbParentFactoryInfo.getCompanyName());
                cell1.setCellStyle(setBorder);
                if (sonFactoryInfos != null && sonFactoryInfos.size() > 0) {
                    for (int j = 0; j < sonFactoryInfos.size(); j++) {
                        PcbSonFactoryInfo pcbSonFactoryInfo = sonFactoryInfos.get(j);
                        Cell cell7 = rowTitle2.createCell(colIndex);
                        cell7.setCellValue(pcbSonFactoryInfo.getSonFactoryName());
                        cell7.setCellStyle(setBorder);
                        Cell cell9 = rowTitle3.createCell(colIndex);
                        Cell cell92 = rowTitle4.createCell(colIndex);
                        if (map.containsKey(pcbSonFactoryInfo.getPcbSonFactoryId())) {
                            cell9.setCellValue(map.get(pcbSonFactoryInfo.getPcbSonFactoryId()).getIsSatisfied());
                            cell9.setCellStyle(setBorder2);
                            cell92.setCellValue(map.get(pcbSonFactoryInfo.getPcbSonFactoryId()).getReason());
                            cell92.setCellStyle(setBorder2);
                        }
                        colIndex++;
                    }
                } else {
                    colIndex++;
                }
                if (colIndex - 1 > flag) {
                    CellRangeAddress region = new CellRangeAddress(t1RowFlag, t1RowFlag, flag, colIndex - 1);
                    sheet.addMergedRegion(region);
                }
            }
            for (int i = 0; i <= rowIndex; i++) {
                Row rowT = sheet.getRow(i);
                for (int j = 0; j < colIndex; j++) {
                    if (rowT.getCell(j) == null) {
                        Cell cell7 = rowT.createCell(j);
                        cell7.setCellStyle(setBorder2);
                    }

                }
            }
            String filename = "pcb能力匹配" + String.valueOf(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(new Date());
            File folder = new File(rootPath + "pcb\\" + format);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            String filePath = rootPath + "pcb\\" + format + "\\" + filename + ".xlsx";
            FileOutputStream outputStream = new FileOutputStream(filePath);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
            return ResultUtil.success(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }

    }

    @Override
    public List<FactoryInfoVM> getAllCapacityInfo() {
        List<FactoryInfoVM> result = new ArrayList<>();
        PcbSonFactoryInfo search = new PcbSonFactoryInfo();
        search.setStatus(1);
        List<PcbSonFactoryInfo> sonFactoryInfoList = pcbSonFactoryInfoDao.getAllByLimit(search);

        for (int i = 0; i < sonFactoryInfoList.size(); i++) {
            List<MaterialVM> pcbMaterialDataByFactory = pcbMaterialService.getPcbMaterialDataByFactory(sonFactoryInfoList.get(i));
            List<CapacityMatchData> capacityMatchDataList = getPcbMatchValueByFactory(sonFactoryInfoList.get(i));
            List<SpecialProcessVM> pcbSpecialProcessInfos = pcbSpecialProcessService.getPcbSpecialProcessDataByFactory(null, sonFactoryInfoList.get(i));

            PcbParentFactoryInfo pcbParentFactoryInfo = pcbParentFactoryInfoService.getById(sonFactoryInfoList.get(i).getParentId());
            FactoryInfoVM factoryInfoVM = new FactoryInfoVM();
            factoryInfoVM.setFactoryName(sonFactoryInfoList.get(i).getSonFactoryName());
            factoryInfoVM.setPcbSize(capacityMatchDataList);
            factoryInfoVM.setMaterial(pcbMaterialDataByFactory);
            factoryInfoVM.setSpecialProcess(pcbSpecialProcessInfos);
            factoryInfoVM.setCompanyName(pcbParentFactoryInfo.getCompanyName());
            factoryInfoVM.setCompanyCode(pcbParentFactoryInfo.getCompanyCode());
            factoryInfoVM.setCompanyNameFull(pcbParentFactoryInfo.getCompanyNameFull());
            result.add(factoryInfoVM);
        }
        return result;
    }


    @Value("${personal.config.httpUrl.getBoardList}")
    String getBoardListApi;

    @Override
    public Result getBoardList(String version,String searchK,String searchV) {
        try {
            if(StringUtils.isBlank(searchV)){
                searchV = null;
            }
            else{
                searchV = searchV.toLowerCase();
            }
            Map<String, List<BoardInfo>> map = new HashMap<>();
            String specialProcessName = "specialProcessName".equals(searchK) ? searchV : null;
            String boardNameS = "boardName".equals(searchK) ? searchV : null;
            String productCode0301S = "productCode0301".equals(searchK) ? searchV : null;
            String versionS = "version".equals(searchK) ? searchV : null;
            String createUserNameS = "createUserName".equals(searchK) ? searchV : null;
            String currentNodeS = "currentNode".equals(searchK) ? searchV : null;
            String currentNodeUserNameS = "currentNodeUserName".equals(searchK) ? searchV : null;
            String projectStatus = "status".equals(searchK) ? searchV : null;

            List<PcbSpecialProcessInfo> PcbSpecialProcessInfoList = pcbSpecialProcessService.getAllByLimit(specialProcessName, null, version, 1);
            for (int i = 0; i < PcbSpecialProcessInfoList.size(); i++) {
                map.put(PcbSpecialProcessInfoList.get(i).getPcbSpecialProcessName(), new ArrayList<BoardInfo>());
            }

            String md5Sign = "6244832a706bbb2c81fb093367027f56";
            MultipartEntityBuilder params = MultipartEntityBuilder.create();
            params.addTextBody("signature", md5Sign);
            String res = HttpUtil.sendPostFormData(getBoardListApi, params);

            JSONObject jsonObject = JSON.parseObject(res);
            if (jsonObject.getInteger("code") == 200) {
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jo = jsonArray.getJSONObject(i);
                    JSONArray boardParamValueList = jo.getJSONArray("boardParamValueList");
                    JSONObject currentProjectNode = jo.getJSONObject("currentProjectNode");
                    Integer projectId = jo.getInteger("projectId");
                    String boardName = "";
                    String version0301 = "";
                    String productCode0301 = "";
                    String status = "";
                    String createUserName = "";
                    String createTime = "";
                    String currentNode = "";
                    String currentNodeUserName = "";
                    if (boardParamValueList == null) {
                        continue;
                    }
                    productCode0301 = jo.getString("projectCode0301");
                    version0301 = jo.getString("projectVersion");
                    Integer creatorId = jo.getInteger("creatorId");
                    if (creatorId != null) {
                        final User userInfoById = userDao.getUserInfoById(creatorId);
                        createUserName = userInfoById.getNickNameCn();
                    }
                    if (currentProjectNode != null) {
                        currentNode = currentProjectNode.getString("nodeNameCn");
                        final JSONObject owner = currentProjectNode.getJSONObject("owner");
                        if (owner != null) {
                            currentNodeUserName = owner.getString("nickNameCn");
                        }
                    }
                    for (int j = 0; j < boardParamValueList.size(); j++) {
                        JSONObject jo2 = boardParamValueList.getJSONObject(j);
                        String boardParamKey = jo2.getString("boardParamKey");
                        String paramValue = jo2.getString("boardParamValue");
                        if (boardParamKey.equals("productBoardName") && !StringUtils.isBlank(paramValue)) {
                            boardName = paramValue;
                        }

                        if (boardParamKey.equals("projectStatus") && !StringUtils.isBlank(paramValue)) {
                            if (paramValue == "2")
                                status = "进行中";
                            if (paramValue == "3")
                                status = "已关闭";
                            if (paramValue == "4")
                                status = "已完成";
                        }

                        if (boardParamKey.equals("createTime") && !StringUtils.isBlank(paramValue)) {
                            createTime = paramValue;
                        }
                    }
                    for (int j = 0; j < boardParamValueList.size(); j++) {
                        JSONObject jo2 = boardParamValueList.getJSONObject(j);
                        String boardParamName = jo2.getString("boardParamName");
                        String paramValue = jo2.getString("boardParamValue");
                        if (map.containsKey(boardParamName)) {
                            if (!StringUtils.isBlank(paramValue) && paramValue.equals("是") && !StringUtils.isBlank(boardName))//&& paramValue.equals("是")
                            {
                                List<BoardInfo> specialProcessList = map.get(boardParamName);
                                BoardInfo boardInfo = new BoardInfo();
                                boardInfo.setBoardName(boardName);
                                boardInfo.setProjectId(projectId);
                                boardInfo.setCreateTime(createTime);
                                boardInfo.setProductCode0301(productCode0301);
                                boardInfo.setVersion(version0301);
                                boardInfo.setCreateUserName(createUserName);
                                boardInfo.setStatus(status);
                                boardInfo.setCurrentNode(currentNode);
                                boardInfo.setCurrentNodeUserName(currentNodeUserName);
                                if(!StringUtils.isBlank(searchK) && !StringUtils.isBlank(searchV)){
                                    if(!StringUtils.isBlank(boardNameS) ){
                                        if(!StringUtils.isBlank(boardInfo.getBoardName()) && boardInfo.getBoardName().toLowerCase().contains(boardNameS)){
                                            specialProcessList.add(boardInfo);
                                        }
                                    }
                                    else if(!StringUtils.isBlank(productCode0301S)){
                                        if(!StringUtils.isBlank(boardInfo.getProductCode0301()) && boardInfo.getProductCode0301().toLowerCase().contains(productCode0301S)){
                                            specialProcessList.add(boardInfo);
                                        }
                                    }
                                    else if(!StringUtils.isBlank(versionS)){
                                        if(!StringUtils.isBlank(boardInfo.getVersion()) && boardInfo.getVersion().toLowerCase().contains(versionS)){
                                            specialProcessList.add(boardInfo);
                                        }
                                    }
                                    else if(!StringUtils.isBlank(createUserNameS)){
                                        if(!StringUtils.isBlank(boardInfo.getCreateUserName()) && boardInfo.getCreateUserName().toLowerCase().contains(createUserNameS)){
                                            specialProcessList.add(boardInfo);
                                        }
                                    }
                                    else if(!StringUtils.isBlank(currentNodeS)){
                                        if(!StringUtils.isBlank(boardInfo.getCurrentNode()) && boardInfo.getCurrentNode().toLowerCase().contains(currentNodeS)){
                                            specialProcessList.add(boardInfo);
                                        }
                                    }
                                    else if(!StringUtils.isBlank(currentNodeUserNameS)){
                                        if(!StringUtils.isBlank(boardInfo.getCurrentNodeUserName()) && boardInfo.getCurrentNodeUserName().toLowerCase().contains(currentNodeUserNameS)){
                                            specialProcessList.add(boardInfo);
                                        }
                                    }
                                    else if(!StringUtils.isBlank(projectStatus)){
                                        if(!StringUtils.isBlank(boardInfo.getStatus()) && boardInfo.getStatus().toLowerCase().contains(projectStatus)){
                                            specialProcessList.add(boardInfo);
                                        }
                                    }
                                }
                                else{
                                    specialProcessList.add(boardInfo);
                                }

                            }
                        }
                    }
                }
            }
            return ResultUtil.success(map);
        } catch (Exception e) {
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }

    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result submitApplication(String data) {
        String userId = UserHeaderHolder.getUserId();
        JSONObject jsonObject = JSONObject.parseObject(data);

        Integer factoryId = jsonObject.getInteger("factoryId");
        String info = jsonObject.getString("info");
        JSONArray fileList = jsonObject.getJSONArray("fileList");

        if (factoryId == null) {
            return ResultUtil.error(500, "factoryId 为空", "factoryId is null", null);
        }
        int flowType = 4;//开放能力
        PcbSonFactoryInfo sonFactoryInfo = pcbSonFactoryInfoDao.getById(factoryId);
        try {
            PcbApproveConfig approveConfig = pcbApproveConfigDao.getOneByLimit(flowType, null, factoryId);
            if (approveConfig == null) {
                return ResultUtil.error(500, "请先配置" + "相关流程的审核人员", "Fail", null);
            }
            PcbCapacityDataApprove search = new PcbCapacityDataApprove();
            search.setFactoryId(factoryId);
            search.setFlowType(flowType);
            search.setStatus(1);
            List<PcbCapacityDataApprove> byLimit = pcbCapacityDataApproveDao.getByLimit(search);
            if (byLimit.size() > 0) {
                for (int i = 0; i < byLimit.size(); i++) {
                    if (byLimit.get(i).getApproveStatus().equals(DB2Config.CapacityDataStatus_Wancheng)) {
                        byLimit.get(i).setStatus(2);//将之前的都作废
                        pcbCapacityDataApproveDao.update(byLimit.get(i));
                    } else {
                        return ResultUtil.error(500, "当前厂家有未处理完成的任务", "", null);
                    }
                }
            }
            //创建流程
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String currentDate = sdf.format(new Date());
            PcbCapacityDataApprove byFlowNum = pcbCapacityDataApproveDao.getByFlowNum(currentDate);
            int currentSeq = 0;
            String flowNum = "";
            if (byFlowNum != null) {
                currentSeq = byFlowNum.getSeq();
            }
            currentSeq++;
            //添加审批记录
            flowNum = currentDate + String.format("%05d", currentSeq);
            PcbCapacityDataApprove pcbCapacityDataApprove1 = new PcbCapacityDataApprove();
            pcbCapacityDataApprove1.setFlowNum(flowNum);
            pcbCapacityDataApprove1.setSeq(currentSeq);
            pcbCapacityDataApprove1.setFlowType(flowType);
            pcbCapacityDataApprove1.setFactoryId(sonFactoryInfo.getPcbSonFactoryId());
            pcbCapacityDataApprove1.setApproveStatus(DB2Config.CapacityDataStatus_H3CAudit);
            pcbCapacityDataApprove1.setCreateTime(new Date());
            pcbCapacityDataApprove1.setCreateUser(userId);
            pcbCapacityDataApprove1.setApproveUserId(approveConfig.getOperator().toString());
            pcbCapacityDataApprove1.setStatus(1);
            pcbCapacityDataApproveDao.insert(pcbCapacityDataApprove1);
            //添加审批详情
            PcbCapacityApproveDetail pcbCapacityApproveDetail = new PcbCapacityApproveDetail();
            pcbCapacityApproveDetail.setFlowType(flowType);
            pcbCapacityApproveDetail.setDataId(pcbCapacityDataApprove1.getId());
            pcbCapacityApproveDetail.setApproveNode(DB2Config.CapacityDataStatus_CreateFlow);
            pcbCapacityApproveDetail.setApplyUserId(Integer.parseInt(userId));
            pcbCapacityApproveDetail.setDepartmentId(null);
            pcbCapacityApproveDetail.setSonFactoryId(sonFactoryInfo.getPcbSonFactoryId());
            pcbCapacityApproveDetail.setFileIds(null);
            pcbCapacityApproveDetail.setRemark(info);
            pcbCapacityApproveDetail.setCreateTime(new Date());
            pcbCapacityApproveDetail.setCreateUser(userId);
            pcbCapacityApproveDetail.setStatus(1);
            pcbCapacityApproveDetail.setSort(100);
            pcbCapacityApproveDetail.setNextNodeUserId(approveConfig.getOperator());
            pcbCapacityApproveDetailDao.insert(pcbCapacityApproveDetail);
            //添加文件
            if (fileList != null) {
                for (int i = 0; i < fileList.size(); i++) {
                    JSONObject joFile = (JSONObject) fileList.getJSONObject(i);
                    PcbCapacityApproveDetailFile pcbCapacityApproveDetailFile = new PcbCapacityApproveDetailFile();
                    pcbCapacityApproveDetailFile.setFlowType(flowType);
                    pcbCapacityApproveDetailFile.setDataId(pcbCapacityDataApprove1.getId());
                    pcbCapacityApproveDetailFile.setDetailDataId(pcbCapacityApproveDetail.getId());
                    pcbCapacityApproveDetailFile.setFileName(joFile.getString("oldName"));
                    pcbCapacityApproveDetailFile.setFileRelatePath(joFile.getString("relatePath"));
                    pcbCapacityApproveDetailFile.setUrl(joFile.getString("url"));
                    pcbCapacityApproveDetailFile.setRemark(joFile.getString("remark"));
                    pcbCapacityApproveDetailFile.setSecretKey(joFile.getString("secretKey"));
                    pcbCapacityApproveDetailFile.setFileSid(joFile.getString("fileSid"));
                    pcbCapacityApproveDetailFile.setCreateTime(new Date());
                    pcbCapacityApproveDetailFile.setCreateUser(userId);
                    int count = pcbCapacityApproveDetailFileDao.insert(pcbCapacityApproveDetailFile);
                }
            }
            //添加审批过程记录
            PcbApproveProcess pcbApproveProcess = new PcbApproveProcess();
            pcbApproveProcess.setApproveType(flowType);
            pcbApproveProcess.setDataId(pcbCapacityDataApprove1.getId());
            pcbApproveProcess.setOldStatus("");
            pcbApproveProcess.setNewStatus(DB2Config.CapacityDataStatus_CreateFlow);
            pcbApproveProcess.setApproveNode(DB2Config.CapacityDataStatus_CreateFlow);
            pcbApproveProcess.setCreateTime(new Date());
            pcbApproveProcess.setApproveUserId(Integer.parseInt(userId));
            pcbApproveProcess.setApplyToId(null);
            pcbApproveProcessDao.insert(pcbApproveProcess);
            //添加审批详情
            PcbCapacityApproveDetail pcbCapacityApproveDetail2 = new PcbCapacityApproveDetail();
            pcbCapacityApproveDetail2.setFlowType(flowType);
            pcbCapacityApproveDetail2.setDataId(pcbCapacityDataApprove1.getId());
            pcbCapacityApproveDetail2.setApproveNode(DB2Config.CapacityDataStatus_H3CAudit);
            pcbCapacityApproveDetail2.setApplyUserId(Integer.parseInt(userId));
            pcbCapacityApproveDetail2.setSonFactoryId(sonFactoryInfo.getPcbSonFactoryId());
            pcbCapacityApproveDetail2.setCreateTime(new Date());
            pcbCapacityApproveDetail2.setCreateUser(userId);
            pcbCapacityApproveDetail2.setStatus(1);
            pcbCapacityApproveDetail2.setSort(100);
            pcbCapacityApproveDetail2.setNextNodeUserId(approveConfig.getOperator2());
            pcbCapacityApproveDetailDao.insert(pcbCapacityApproveDetail2);
            //添加审批过程记录
            PcbApproveProcess pcbApproveProcess2 = new PcbApproveProcess();
            pcbApproveProcess2.setApproveType(flowType);
            pcbApproveProcess2.setDataId(pcbCapacityDataApprove1.getId());
            pcbApproveProcess2.setOldStatus(DB2Config.CapacityDataStatus_CreateFlow);
            pcbApproveProcess2.setNewStatus(DB2Config.CapacityDataStatus_H3CAudit);
            pcbApproveProcess2.setApproveNode(DB2Config.CapacityDataStatus_H3CAudit);
            pcbApproveProcess2.setCreateTime(new Date());
            pcbApproveProcess2.setApplyToId(null);
            pcbApproveProcessDao.insert(pcbApproveProcess2);
            User userInfo = userDao.getUserInfoById(Integer.parseInt(userId));
            try {
                if (!StringUtils.isBlank(env) && env.equals("h3c_pro")) {
                    List<MailAddress> mailAddressList = new ArrayList<>();
                    if(userInfo.getEmail().contains(",")){
                        String[] emailsArr = userInfo.getEmail().split(",");
                        for (String email : emailsArr) {
                            MailAddress mailAddress = new MailAddress();
                            mailAddress.setMailAddress(email);
                            mailAddress.setType(0);
                            mailAddressList.add(mailAddress);
                        }
                    }else{
                        MailAddress mailAddress = new MailAddress();
                        mailAddress.setMailAddress(userInfo.getEmail());
                        mailAddress.setType(0);
                        mailAddressList.add(mailAddress);
                    }

                    thirdApiService.sendMail(userInfo.getUserName(), "PCB开放能力数据审批", "PCB开放能力数据审批",
                            "您有待处理的任务，请及时处理", "10086", mailAddressList, null, null, null, null, 2, null);

                    System.out.println("send mail success");
                }
            } catch (Exception e) {
                System.out.println("send mail error :" + e.getMessage());
            }

            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            ;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }

    }


    @Override
    public List<PcbOpenCapacityAuthentication> getAuthencationData(Integer approveStatus) {
        PcbOpenCapacityAuthentication search1 = new PcbOpenCapacityAuthentication();
        search1.setApproveStatus(approveStatus);
        List<PcbOpenCapacityAuthentication> pcbOpenCapacityAuthenticationList = pcbOpenCapacityAuthenticationDao.getAllByLimit(search1);
        for (int i = 0; i < pcbOpenCapacityAuthenticationList.size(); i++) {
            PcbOpenCapacityAuthentication pcbOpenCapacityAuthentication = pcbOpenCapacityAuthenticationList.get(i);
            PcbOpenCapacityFile param = new PcbOpenCapacityFile();
            param.setPcbAuthenticationId(pcbOpenCapacityAuthentication.getId());
            PcbSonFactoryInfo factoryInfo = pcbSonFactoryInfoDao.getById(pcbOpenCapacityAuthentication.getFactoryId());
            pcbOpenCapacityAuthentication.setPcbSonFactoryInfo(factoryInfo);
            List<PcbOpenCapacityFile> pcbOpenCapacityFileList = pcbOpenCapacityFileDao.getAllByLimit(param);
//            pcbOpenCapacityAuthentication.setApplyFiles(pcbOpenCapacityFileList.stream().filter(x -> x.getStep() == 1).collect(Collectors.toList()));
//            pcbOpenCapacityAuthentication.setApplyFiles2(pcbOpenCapacityFileList.stream().filter(x -> x.getStep() == 3).collect(Collectors.toList()));
//            pcbOpenCapacityAuthentication.setH3cFiles(pcbOpenCapacityFileList.stream().filter(x -> x.getStep() == 2).collect(Collectors.toList()));
        }
        return pcbOpenCapacityAuthenticationList;
    }

    @Override
    public List<PcbOpenCapacityApproveProcess> getApproveProcess(Integer dataId) {
        PcbOpenCapacityApproveProcess search = new PcbOpenCapacityApproveProcess();
        search.setDataId(dataId);
        List<PcbOpenCapacityApproveProcess> pcbOpenCapacityApproveProcessesList = pcbOpenCapacityApproveProcessDao.getByLimit(search);
        for (int i = 0; i < pcbOpenCapacityApproveProcessesList.size(); i++) {
            String fileIds = pcbOpenCapacityApproveProcessesList.get(i).getFileIds();
            if (!StringUtils.isBlank(fileIds)) {
                List<PcbOpenCapacityFile> fileList = new ArrayList<>();
                String[] fileIdArray = fileIds.split(",");
                for (int j = 0; j < fileIdArray.length; j++) {
                    PcbOpenCapacityFile pcbOpenCapacityFile = pcbOpenCapacityFileDao.getById(Integer.parseInt(fileIdArray[j]));
                    fileList.add(pcbOpenCapacityFile);
                }
                pcbOpenCapacityApproveProcessesList.get(i).setFileList(fileList);
            }
        }
        return pcbOpenCapacityApproveProcessesList;
    }


    public List<CapacityMatchData> getPcbMatchValueByFactory(PcbSonFactoryInfo pcbSonFactoryInfo) {
        List<CapacityMatchData> capacityMatchDataList = new ArrayList<>();
        PcbSizeFactoryValue search = new PcbSizeFactoryValue();
        search.setSonFactoryId(pcbSonFactoryInfo.getPcbSonFactoryId());
        List<PcbSizeFactoryValue> pcbSizeFactoryValueList = pcbMatchFactoryValueDao.getByLimit(search);
        if (pcbSizeFactoryValueList != null) {
            Map<String, String> map = new HashMap<>();
            for (int i = 0; i < pcbSizeFactoryValueList.size(); i++) {
                String key = pcbSizeFactoryValueList.get(i).getSonFactoryId() + "-" + pcbSizeFactoryValueList.get(i).getPcbMatchParamKey();
                map.put(key, pcbSizeFactoryValueList.get(i).getPcbMatchParamValue());
            }
            PcbSizeParam search2 = new PcbSizeParam();
            search2.setStatus(1);
            List<PcbSizeParam> pcbSizeParamList = pcbMatchParamDao.getByLimit(search2);

            for (int i = 0; i < pcbSizeParamList.size(); i++) {
                String paramKey = pcbSizeParamList.get(i).getPcbMatchParamKey();
                CapacityMatchData capacityMatchData = new CapacityMatchData();
                capacityMatchData.setBigType("PCB尺寸");
                capacityMatchData.setParamName(pcbSizeParamList.get(i).getPcbMatchParamName());
                capacityMatchData.setParamKey(pcbSizeParamList.get(i).getPcbMatchParamKey());
                capacityMatchData.setParamRule(pcbSizeParamList.get(i).getPcbMatchParamRuleType());
                String key2 = pcbSonFactoryInfo.getPcbSonFactoryId() + "-" + paramKey;
                if (map.containsKey(key2)) {
                    capacityMatchData.setParamValue(map.get(key2));
                } else {
                    capacityMatchData.setParamValue(null);
                }
                capacityMatchDataList.add(capacityMatchData);
            }
        }
        return capacityMatchDataList;
    }

    @Override
    public Result outputMatchFactoryValue(List<Integer> sonFactoryInfoList, int type){
        try{
            final List<CapacityMatchData> matchFactoryValue = getMatchFactoryValue(sonFactoryInfoList, type);

            List<PcbSonFactoryInfo> factoryInfos = new ArrayList<>();
            for (int i = 0; i < sonFactoryInfoList.size(); i++) {
                Integer idi = sonFactoryInfoList.get(i);
                PcbSonFactoryInfo sonFactoryInfo = pcbSonFactoryInfoDao.getById(idi);
                factoryInfos.add(sonFactoryInfo);
            }
            // 创建工作簿对象
            Workbook workbook = new XSSFWorkbook();
            // 创建工作表对象
            Sheet sheet = workbook.createSheet("Sheet1");
            XSSFCellStyle setBorder = (XSSFCellStyle) workbook.createCellStyle();
            setBorder.setBorderBottom(BorderStyle.THIN);
            setBorder.setBorderLeft(BorderStyle.THIN);
            setBorder.setBorderRight(BorderStyle.THIN);
            setBorder.setBorderTop(BorderStyle.THIN);
            setBorder.setVerticalAlignment(VerticalAlignment.CENTER);
            setBorder.setAlignment(HorizontalAlignment.LEFT);
            //创建字体 加粗
            XSSFFont font = (XSSFFont) workbook.createFont();
            font.setBold(true);
            font.setFontHeight(11);
            setBorder.setFont(font);
            XSSFCellStyle setBorder2 = (XSSFCellStyle) workbook.createCellStyle();
            setBorder2.setBorderBottom(BorderStyle.THIN);
            setBorder2.setBorderLeft(BorderStyle.THIN);
            setBorder2.setBorderRight(BorderStyle.THIN);
            setBorder2.setBorderTop(BorderStyle.THIN);
            setBorder2.setVerticalAlignment(VerticalAlignment.CENTER);
            setBorder2.setAlignment(HorizontalAlignment.LEFT);

            Row rowT1 = sheet.createRow(1);
            Cell cell10 = rowT1.createCell(0);
            cell10.setCellValue("大类");
            Cell cell11 = rowT1.createCell(1);
            cell11.setCellValue("名称");

            Row rowT2 = sheet.createRow(2);
            int columIndex=2;
            List<Integer> pcbFactoryIds_new = new ArrayList<>();
            List<PcbParentFactoryInfo> pcbParentFactoryInfoList = pcbParentFactoryInfoService.getBySonList(sonFactoryInfoList, null);
            for (int i = 0; i < pcbParentFactoryInfoList.size(); i++) {
                Cell celli = rowT1.createCell(columIndex);
                celli.setCellStyle(setBorder);
                celli.setCellValue(pcbParentFactoryInfoList.get(i).getCompanyName());
                int startIndexT = columIndex;
                List<PcbSonFactoryInfo> sonFactoryInfos = pcbParentFactoryInfoList.get(i).getSonFactoryInfos();
                if (sonFactoryInfos != null && sonFactoryInfos.size() > 0) {
                    for (int j = 0; j < sonFactoryInfos.size(); j++) {
                        Cell cell2j = rowT2.createCell(columIndex);
                        cell2j.setCellValue(sonFactoryInfos.get(j).getSonFactoryName());
                        cell2j.setCellStyle(setBorder);
                        columIndex++;
                        pcbFactoryIds_new.add(sonFactoryInfos.get(j).getPcbSonFactoryId());
                    }
                    CellRangeAddress region3 = new CellRangeAddress(1, 1, startIndexT, columIndex - 1);
                    if (columIndex - 1 > startIndexT) {
                        sheet.addMergedRegion(region3);
                    }
                }
                else {
                    columIndex++;
                }
            }

            int rowIndex = 3;
            for(int i=0;i<matchFactoryValue.size();i++){
                Row rowi = sheet.createRow(rowIndex);
                rowIndex++;
                String bigType  = matchFactoryValue.get(i).getBigType();
                Cell celli0= rowi.createCell(0);
                celli0.setCellValue(bigType);
                Cell celli1= rowi.createCell(1);
                celli1.setCellValue(matchFactoryValue.get(i).getParamName());

                final List<ParamData> factoryData = matchFactoryValue.get(i).getFactoryData();
                int colIndex2 = 2;
                for (int j = 0; j < pcbFactoryIds_new.size(); j++){
                    Integer fid = pcbFactoryIds_new.get(j);
                    Cell cellij= rowi.createCell(colIndex2);
                    colIndex2++;
                    final List<ParamData> collect = factoryData.stream().filter(x -> x.getSonFactoryId().equals(fid)).collect(Collectors.toList());
                    if(collect.size()>0){
                        String value  = collect.get(0).getValue();
                        if(!StringUtils.isBlank(value)){
                            if(bigType.equals("板材")){
                                if(value.equals("1")){
                                    cellij.setCellValue("I级开放");
                                }
                                if(value.equals("2")){
                                    cellij.setCellValue("II级开放");
                                }
                                if(value.equals("3")){
                                    cellij.setCellValue("III级开放");
                                }
                                if(value.equals("4")){
                                    cellij.setCellValue("不开放");
                                }
                            }
                            else if(bigType.equals("特殊工艺")){
                                if(value.equals("1")){
                                    cellij.setCellValue("满足");
                                }
                                if(value.equals("2")){
                                    cellij.setCellValue("不满足");
                                }
                            }
                            else if(bigType.equals("PCB尺寸")){
                                cellij.setCellValue(value);
                            }
                        }
                        else{
                            cellij.setCellValue("");
                        }

                    }
                    else{
                        cellij.setCellValue("");
                    }
                }
            }

            //加边框
            int columnCount = 2 + pcbFactoryIds_new.size();
            for (int i = 3; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                for (int j = 0; j < columnCount; j++) {
                    Cell celli = row.getCell(j);
                    if (celli == null) {
                        celli = row.createCell(j);
                        celli.setCellStyle(setBorder2);
                    } else {
                        if (celli.getCellStyle() == null) {
                            celli.setCellStyle(setBorder2);
                        } else {
                            if (celli.getCellStyle().getFillForegroundColor() != IndexedColors.GREEN.getIndex()
                                    && celli.getCellStyle().getFillForegroundColor() != IndexedColors.RED.getIndex()) {
                                celli.setCellStyle(setBorder2);
                            }
                        }
                    }
                }
            }
            for (int i = 1; i <= 2; i++) {
                Row row = sheet.getRow(i);
                for (int j = 0; j < columnCount; j++) {
                    Cell celli = row.getCell(j);
                    if (celli == null) {
                        celli = row.createCell(j);
                        celli.setCellStyle(setBorder);
                    } else {
                        if (celli.getCellStyle() == null) {
                            celli.setCellStyle(setBorder);
                        } else {
                            if (celli.getCellStyle().getFillForegroundColor() != IndexedColors.GREEN.getIndex()
                                    && celli.getCellStyle().getFillForegroundColor() != IndexedColors.RED.getIndex()) {
                                celli.setCellStyle(setBorder);
                            }
                        }
                    }
                }
            }
            //合并单元格
            sheet.addMergedRegion(new CellRangeAddress(1, 2, 0, 0));
            sheet.addMergedRegion(new CellRangeAddress(1, 2, 1, 1));

            sheet.setColumnWidth(0, 15 * 256);
            sheet.setColumnWidth(1, 15 * 256);
            for (int i = 0; i < factoryInfos.size() ; i++) {
                sheet.setColumnWidth(2 + i, 12 * 256);
            }

            // 导出Excel文件
            String filename = (type == 1? "基础能力数据":"开放能力数据") + String.valueOf(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(new Date());
            String filePath = rootPath + "pcb\\" + format + "\\" + filename + ".xlsx";
            File folder = new File(rootPath + "pcb\\" + format);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            FileOutputStream outputStream = new FileOutputStream(filePath);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
            return ResultUtil.success(filePath);
        }
        catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }

    }

    @Override
    public Result outputBoardList(String version){
        try{
            final Result result = getBoardList(version,null,null);
            if(result.getCode().equals(200)){
                if(result.getData()!=null){
                    Map<String, List<BoardInfo>> map = (Map<String, List<BoardInfo>>)result.getData();
                    Workbook workbook = new XSSFWorkbook();
                    Sheet sheet = workbook.createSheet("Sheet1");
                    XSSFCellStyle setBorder = getStyle1(workbook);//字体加粗
                    XSSFCellStyle setBorder2 = getStyle2(workbook);//字体不加粗
                    final XSSFCellStyle dateStyle = getDateStyle(workbook);

                    Row rowT1 = sheet.createRow(1);
                    Cell cell10 = rowT1.createCell(0);
                    cell10.setCellValue("序号");
                    cell10.setCellStyle(setBorder);
                    Cell cell11 = rowT1.createCell(1);
                    cell11.setCellValue("特殊工艺名称");
                    cell11.setCellStyle(setBorder);
                    Cell cell12 = rowT1.createCell(2);
                    cell12.setCellValue("单板");
                    cell12.setCellStyle(setBorder);
                    Cell cell13 = rowT1.createCell(3);
                    cell13.setCellValue("0301编码");
                    cell13.setCellStyle(setBorder);
                    Cell cell14 = rowT1.createCell(4);
                    cell14.setCellValue("版本");
                    cell14.setCellStyle(setBorder);
                    Cell cell15 = rowT1.createCell(5);
                    cell15.setCellValue("创建时间");
                    cell15.setCellStyle(setBorder);
                    Cell cell16 = rowT1.createCell(6);
                    cell16.setCellValue("创建人");
                    cell16.setCellStyle(setBorder);
                    Cell cell17 = rowT1.createCell(7);
                    cell17.setCellValue("当前节点");
                    cell17.setCellStyle(setBorder);
                    Cell cell18 = rowT1.createCell(8);
                    cell18.setCellValue("当前节点责任人");
                    cell18.setCellStyle(setBorder);
                    Cell cell19 = rowT1.createCell(9);
                    cell19.setCellValue("项目状态");
                    cell19.setCellStyle(setBorder);
                    int rowIndex = 1;
                    for(Map.Entry<String, List<BoardInfo>> entry : map.entrySet()){
                        List<BoardInfo> boardInfoList = entry.getValue();
                        if(boardInfoList == null){
                            continue;
                        }
                        for(int i=0;i<boardInfoList.size();i++){
                            Row row = sheet.createRow(rowIndex);

                            Cell celli0 = row.createCell(0);
                            celli0.setCellValue(rowIndex);
                            Cell celli1 = row.createCell(1);
                            celli1.setCellValue(entry.getKey());
                            Cell celli2 = row.createCell(2);
                            celli2.setCellValue(boardInfoList.get(i).getBoardName());
                            Cell celli3 = row.createCell(3);
                            celli3.setCellValue(boardInfoList.get(i).getProductCode0301());
                            Cell celli4 = row.createCell(4);
                            celli4.setCellValue(boardInfoList.get(i).getVersion());
                            Cell celli5 = row.createCell(5);
                            celli5.setCellValue(boardInfoList.get(i).getCreateTime());
                            Cell celli6 = row.createCell(6);
                            celli6.setCellValue(boardInfoList.get(i).getCreateUserName());
                            Cell celli7 = row.createCell(7);
                            celli7.setCellValue(boardInfoList.get(i).getCurrentNode());
                            Cell celli8 = row.createCell(8);
                            celli8.setCellValue(boardInfoList.get(i).getCurrentNodeUserName());
                            Cell celli9 = row.createCell(9);
                            celli9.setCellValue(boardInfoList.get(i).getStatus());
                            rowIndex++;
                        }

                    }
                    // 导出Excel文件
                    String filename = "特殊工艺父项单板" + String.valueOf(System.currentTimeMillis());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String format = sdf.format(new Date());
                    String filePath = rootPath + "pcb\\" + format + "\\" + filename + ".xlsx";
                    File folder = new File(rootPath + "pcb\\" + format);
                    if (!folder.isDirectory()) {
                        folder.mkdirs();
                    }
                    FileOutputStream outputStream = new FileOutputStream(filePath);
                    workbook.write(outputStream);
                    workbook.close();
                    outputStream.close();
                    return ResultUtil.success(filePath);
                }
                else {
                    return result;
                }

            }
            else {
                return result;
            }
        }
        catch (Exception e){
            return ResultUtil.error(500,e.getMessage(),e.getMessage(),null);
        }

    }

    public XSSFCellStyle getStyle1(Workbook workbook) {
        XSSFCellStyle setBorder = (XSSFCellStyle) workbook.createCellStyle();
        setBorder.setBorderBottom(BorderStyle.THIN);
        setBorder.setBorderLeft(BorderStyle.THIN);
        setBorder.setBorderRight(BorderStyle.THIN);
        setBorder.setBorderTop(BorderStyle.THIN);
        setBorder.setVerticalAlignment(VerticalAlignment.CENTER);
        setBorder.setAlignment(HorizontalAlignment.LEFT);
        //创建字体 加粗
        XSSFFont font = (XSSFFont) workbook.createFont();
        font.setBold(true);
        font.setFontHeight(11);
        setBorder.setFont(font);
        return setBorder;
    }
    //创建日期格式
    public XSSFCellStyle getDateStyle(Workbook workbook) {
        XSSFCellStyle setBorder2 = (XSSFCellStyle) workbook.createCellStyle();
        setBorder2.setBorderBottom(BorderStyle.THIN);
        setBorder2.setBorderLeft(BorderStyle.THIN);
        setBorder2.setBorderRight(BorderStyle.THIN);
        setBorder2.setBorderTop(BorderStyle.THIN);
        setBorder2.setVerticalAlignment(VerticalAlignment.CENTER);
        setBorder2.setAlignment(HorizontalAlignment.LEFT);
        setBorder2.setDataFormat(workbook.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
        return setBorder2;
    }

    public XSSFCellStyle getStyle2(Workbook workbook) {
        XSSFCellStyle setBorder2 = (XSSFCellStyle) workbook.createCellStyle();
        setBorder2.setBorderBottom(BorderStyle.THIN);
        setBorder2.setBorderLeft(BorderStyle.THIN);
        setBorder2.setBorderRight(BorderStyle.THIN);
        setBorder2.setBorderTop(BorderStyle.THIN);
        setBorder2.setVerticalAlignment(VerticalAlignment.CENTER);
        setBorder2.setAlignment(HorizontalAlignment.LEFT);
        return setBorder2;
    }
}
